using Microsoft.AspNetCore.Mvc;
using FServer.Core.Interfaces;

namespace FServer.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class GameController : ControllerBase
{
    private readonly ICacheService _cacheService;
    private readonly ILogger<GameController> _logger;

    public GameController(ICacheService cacheService, ILogger<GameController> logger)
    {
        _cacheService = cacheService;
        _logger = logger;
    }

    [HttpGet("config")]
    public async Task<IActionResult> GetConfig([FromQuery] string? key = null)
    {
        try
        {
            if (string.IsNullOrEmpty(key))
            {
                // 返回所有配置
                var configs = new Dictionary<string, object>
                {
                    ["server_name"] = "FServer",
                    ["version"] = "1.0.0",
                    ["max_players"] = 10000,
                    ["battle_timeout"] = 300,
                    ["energy_recovery_rate"] = 1
                };
                
                return Ok(new { Success = true, Configs = configs });
            }
            else
            {
                // 返回特定配置
                var value = await _cacheService.GetAsync<string>($"config:{key}");
                if (value != null)
                {
                    return Ok(new { Success = true, Key = key, Value = value });
                }
                else
                {
                    return NotFound(new { Success = false, Message = $"Config key '{key}' not found" });
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get config for key: {Key}", key);
            return StatusCode(500, new { Success = false, Message = "Internal server error" });
        }
    }

    [HttpPost("config")]
    public async Task<IActionResult> SetConfig([FromBody] SetConfigRequest request)
    {
        try
        {
            await _cacheService.SetAsync($"config:{request.Key}", request.Value, TimeSpan.FromHours(24));
            
            _logger.LogInformation("Config updated: {Key} = {Value}", request.Key, request.Value);
            
            return Ok(new { Success = true, Message = "Config updated successfully" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to set config: {Key} = {Value}", request.Key, request.Value);
            return StatusCode(500, new { Success = false, Message = "Internal server error" });
        }
    }

    [HttpGet("status")]
    public IActionResult GetStatus()
    {
        var status = new
        {
            Server = "FServer",
            Version = "1.0.0",
            Status = "Running",
            Timestamp = DateTime.UtcNow,
            Uptime = Environment.TickCount64,
            Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Unknown"
        };

        return Ok(status);
    }
}

public class SetConfigRequest
{
    public string Key { get; set; } = string.Empty;
    public string Value { get; set; } = string.Empty;
}
